package com.xuecheng.system.service.impl;

import cn.hutool.crypto.digest.DigestUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.xuecheng.commons.enums.ErrorCode;
import com.xuecheng.commons.model.dto.LoginDto;
import com.xuecheng.commons.model.vo.LoginVo;
import com.xuecheng.commons.model.vo.ResponseResult;
import com.xuecheng.commons.utils.JwtUtils;
import com.xuecheng.system.domain.User;
import com.xuecheng.system.mappers.UserMapper;
import com.xuecheng.system.service.UserService;
import com.xuecheng.web.exceptions.BusinessException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;


import java.util.HashMap;
import java.util.Map;

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;

    //用户登录
    public ResponseResult login(LoginDto dto) {
        //1、验证请求参数（是否为空，是否符合规则），略
        String phone = dto.getUsername();
        String password = dto.getPassword();
        String utype = dto.getUtype();
        //2、根据手机号和类型，查询用户对象
        LambdaQueryWrapper<User> qw = new LambdaQueryWrapper<>();
        qw.eq(User::getPhone,phone);
        qw.eq(User::getUtype,utype);
        User user = userMapper.selectOne(qw);
        //2.1 用户不存在
        if(user == null) {
            //手动抛出异常，在异常处理器统一解决
            throw new BusinessException(ErrorCode.LOGINERROR);
        }
        //2.2 用户存在，比较密码
        String dbPassword = user.getPassword();
        password = DigestUtil.md5Hex(password);//对用户输入的密码加密
        //3、判断用户输入的密码和数据库密码是否一致
        if(!dbPassword.equals(password)) {
            //3.1 密码不一致
            throw new BusinessException(ErrorCode.LOGINERROR);
        }
        //3.2 密码一致
        //4、生成JWT的token字符串
        Map<String,Object> claimMaps = new HashMap<>();
        claimMaps.put("userId",user.getId());
        claimMaps.put("companyId",user.getCompanyId());
        claimMaps.put("companyName",user.getCompanyName());
        String token = JwtUtils.createToken(claimMaps, 240);//存入jwt中的数据，超时时间（单位：分钟）

        //5、构造返回数据
        LoginVo vo = new LoginVo();
        vo.setAccess_token(token);
        vo.setUsername(user.getName());

        return ResponseResult.okResult(vo);
    }
}